<template>
    <div>
        <el-form
            v-if="!_isReadOnly"
            :model="model"
            :rules="rules"
            label-position="top"
            ref="ruleForm"
            label-width="100px">
            <el-form-item label="表单标题" prop="name">
                <el-input type="text" placeholder="请输入表单标题" show-word-limit maxlength="100" :value="model.name" @input="update('name', $event)"></el-input>
            </el-form-item>
            <el-form-item label="表单描述" prop="desc">
                <el-tabs v-model="activeName" @tab-click="handleTabClick">
                    <el-tab-pane label="普通文本" name="text">
                        <el-input
                            type="textarea"
                            :rows="12"
                            placeholder="请输入内容"
                            show-word-limit
                            maxlength="300"
                            :value="model.desc"
                            @input="update('desc', $event)"
                        >
                        </el-input>
                    </el-tab-pane>
                    <el-tab-pane label="富文本" name="rich">
                        <editor
                            v-if="activeName === 'rich'"
                            :value="model.richText"
                            v-model="model.richText"
                            @change="handleChange"
                        ></editor>
                    </el-tab-pane>
                </el-tabs>
            </el-form-item>
            <template v-if="client === 'OPERATION'">
                <el-form-item label="表单分类" class="half-width" prop="typeId" required>
                    <el-select
                        v-model="model.typeId"
                        size="mini"
                        placeholder="请选择表单分类"
                        :disabled="_isReadOnly"
                    >
                        <el-option
                            v-for="item in commonTypeList"
                            :key="item.id"
                            :value="item.id"
                            :label="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
            </template>
            <template v-if="_isTownAdminPage && templateType !== 'all' && !_isDeclare">
                <el-form-item label="所属部门" class="half-width" prop="departmentValue" required>
                    <tree-cascader
                        title="所属部门"
                        v-model="model.departmentValue"
                        :isSingle="false"
                        filterable
                        :checkStrictly="true"
                        :options="departmentList"
                        @sure="changeDepartmentName"
                    >
                        <el-button class="department-btn" plain size="mini">{{ departmentName || "点击所属部门" }}</el-button>
                    </tree-cascader>
                </el-form-item>
            </template>
            <template v-if="_isTownAdminPage && templateType !== 'all' && _isDeclare">
                <el-form-item label="接收人" prop="receiverId" class="half-width" required>
                    <el-button plain size="mini" @click="chooseReceiver">
                        {{ receiverItemList.length ? (receiverItemList[0].departmentName ? receiverItemList[0].departmentName + "/" : "") + receiverItemList[0].name : "选择接收人" }}
                    </el-button>
                </el-form-item>
            </template>
            <template v-if="_isTownAdminPage && templateType !== 'all' && _isDeclare">
                <el-form-item label="分类" prop="categoryId" class="half-width" required>
                    <el-select v-model="model.categoryId" placeholder="请选择">
                        <el-option
                            v-for="(item, index) in typeOptions"
                            :key="index"
                            :value="item.id"
                            :label="item.name">
                            {{ item.name }}
                        </el-option>
                    </el-select>
                </el-form-item>
            </template>
        </el-form>
        <div class="readOnly-form" v-else>
            <div class="group">
                <div>
                    <span class="title">表单标题</span>
                    <p class="name">{{ model.name }}</p>
                </div>
                <div>
                    <span class="title">表单描述</span>
                    <div v-if="model.desc || model.richText">
                        <p v-if="!isSend" v-html="model.desc || model.richText" class="val"></p>
                        <el-button v-if="isSend && !model.desc" size="mini" @click="toPreviewRich">点击查看表单描述</el-button>
                    </div>
                </div>
            </div>
        </div>
        <el-dialog
            title="表单描述"
            :visible.sync="wechatDialogVisible"
            class="wechat-mask"
        >
            <div class="content">
                <p v-html="model.richText"></p>
            </div>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Mixins, Watch } from "vue-property-decorator";
import editor from "@/components/public/editor/index.vue";
import TreeCascader from "@/views/module-manage/src/components/tree-cascader/index.vue";
import FormMixin from "@/mixins/form.mixin.ts";
import { dialogSelect } from "@/views/process-manage/src/components/person-selection/index";
import { State } from "vuex-class";

@Component({
    name: "richTextNotAlive",
    components: {
        editor,
        TreeCascader
    },
    model: { prop: "model", event: "input" }
})
export default class RichText extends Mixins(FormMixin) {
    @State(state => state.user.userInfo) user: any;
    @Prop({ type: Boolean, default: false }) readonly isSend!: boolean;
    @Prop({
        type: Object,
        default: () => {
            return {};
        }
    })
    readonly userLevel!: any;

    @Prop({
        type: Array,
        default: () => {
            return [];
        }
    })
    readonly departmentList!: any[];

    @Prop({
        type: Object,
        default: () => {
            return {};
        }
    })
    readonly model!: any;

    @Prop({
        type: String,
        default: () => {
            return "";
        }
    })
    readonly richTextActiveName!: string;

    rules = {
        name: [
            { required: true, message: "请输入表单标题", trigger: "blur" },
            { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" }
        ],
        typeId: [
            { required: true, message: "请选择表单分类", trigger: "change" }
        ],
        departmentValue: [
            { required: true, message: "请选择所属部门", trigger: "change" }
        ],
        receiverId: [
            { required: true, message: "请选择接收人", trigger: "change" }
        ],
        categoryId: [
            { required: true, message: "请选择分类", trigger: "change" }
        ]
    };

    activeName = "";
    commonTypeList: any[] = [];
    receiverItemList: any[] = [];
    receiverIdList: any[] = [];
    typeOptions: any[] = [];
    categoryId = "";
    departmentName = "";
    wechatDialogVisible = false

    get _isOperation() {
        return ["ADMIN", "OPERATION_ADMIN", "OPERATION"].includes(
            this.userLevel.name
        );
    }

    get _isTownPage() {
        return this.$route.name === "TownModuleManageForm";
    }

    get _isDetail() {
        return this.$route.query.isDetail === "1";
    }

    get _isReadOnly() {
        return this.$route.query.isDetail === '1' || this.$route.query.isSend === 'send';
    }

    get _isOperationPage() {
        return this.$route.name === "OperationModuleManageForm";
    }

    get _isDeclare() {
        return this.$route.query.declareTypeId;
    }

    @Watch("model.departmentValue", { immediate: true, deep: true })
    changeDeptName1() {
        this.reallyChangeDeptName();
    }

    @Watch("departmentList", { immediate: true, deep: true })
    changeDeptName2() {
        this.reallyChangeDeptName();
    }

    created() {
        if (this._isOperationPage) {
            this.getType();
        }
        if (this._isDeclare) {
            this.getTypeOptions();
        }
    }

    mounted() {
        this.activeName = this.richTextActiveName;
        this.receiverIdList = this.$route.query.receiverId ? [this.$route.query.receiverId] : [];
        this.receiverItemList = this.$route.query.receiverId ? [{ id: this.$route.query.receiverId, name: this.$route.query.receiverName }] : [];
    }

    reallyChangeDeptName() {
        if (this.departmentList.length && this.model.departmentValue.length) {
            const resList: any[] = [];
            const getList = (list: any) => {
                list.forEach((item: any) => {
                    if (this.model.departmentValue.includes(item.value)) {
                        resList.push(item);
                    }
                    if (item.children && item.children.length) {
                        getList(item.children);
                    }
                });
            };
            getList(this.departmentList);
            this.departmentName = resList.map((item: any) => item.label).join();
        }
    }

    async getType() {
        const res = await this.$server["business/config/tree"]({
            data: {}
        });
        if (res.data.code === 200) {
            this.commonTypeList = res.data.data[0].children;
        }
    }

    handleChange(val: any) {
        this.model.richText = val;
    }

    update(key: any, value: any) {
        this.model[key] = value;
        this.$emit("input", this.model);
    }

    handleTabClick() {
        this.$emit("activeChane", this.activeName);
    }

    onSubmit() {
        return new Promise((resolve: any, reject: any) => {
            (this.$refs.ruleForm as any).validate((valid: any) => {
                if (valid) {
                    if (this.activeName === "rich" && this.model.richText === "") {
                        reject("请填写表单描述富文本");
                    } else {
                        resolve(true);
                    }
                }
            });
        });
    }

    // 选择接收人
    chooseReceiver() {
        dialogSelect({
            isSingle: true,
            selectedList: this.receiverIdList,
            selectedItemList: this.receiverItemList,
            tabs: [
                {
                    label: "镇成员",
                    name: "town",
                    type: "group"
                }
            ],
            sure: async(vm: any, model: any) => {
                vm.close();
                this.receiverItemList = model.selectedItemList;
                this.receiverIdList = model.selectedList;
                this.model.receiverId = model.selectedList.length ? model.selectedList[0] : "";
                (this.$refs.ruleForm as any).validateField("receiverId");
            },
            getOptions: (vm: any, model: any) => this.getOptions(vm, model)
        });
    }

    // 获取选项
    async getOptions(vm: any, model: any) {
        if (model.name === "town") {
            const res = await this.$server["org/getMember"]({
                data: {
                    departmentId: "",
                    pageSize: 999,
                    currentPage: 1
                },
                loader: false
            });
            if (res.data.code === 200) {
                const arrObj: any = {};
                res.data.data.records.filter((item: any) => item.id !== this.user.id).forEach((item: any) => {
                    if (arrObj[item.departmentId]) {
                        arrObj[item.departmentId].push({
                            ...item,
                            governmentName: item.departmentName
                        });
                    } else {
                        arrObj[item.departmentId] = [{
                            ...item,
                            governmentName: item.departmentName
                        }];
                    }
                });
                vm.getOptions(Object.values(arrObj) || []);
            } else {
                vm.getOptions([]);
            }
        }
    }

    async getTypeOptions() {
        const res = await this.$server["declare/getType"]({
            data: {
                cityCode: this.authArea.cityCode
            }
        });
        if (res.data.code === 200) {
            this.typeOptions = res.data.data[0].children;
            console.log(this.typeOptions);

            this.typeOptions.forEach((item: any) => {
                if (item.id === this.$route.query.declareTypeId) {
                    this.model.categoryId = item.id;
                }
            });
        }
    }

    changeDepartmentName(vm: any, model: any) {
        console.log(vm);
        this.departmentName = model.selectData.map((item: any) => item.label).join();
    }

    toPreviewRich() {
        this.wechatDialogVisible = true;
    }
}
</script>

<style lang="scss" scoped>
.el-form {
    background: #ffffff;
    padding: 0 20px;
    height: 100%;
    overflow-y: auto;
    ::v-deep {
        .el-form-item {
            margin-bottom: 22px!important;
            .el-form-item__label {
                padding: 0;
            }
            .el-tabs {
                .el-tabs__header {
                    background: #f5f5f5;
                }
                .el-tabs__content {
                    .ask-tinymce-editor-box {
                        padding: 0;
                    }
                }
            }
        }
    }
}
.readOnly-form {
    background-color: #ffffff;
    height: 100%;
    overflow: scroll;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    .group {
        width: 843px;
        padding: 31px 0 0 0;
        & > div {
            @include flexLayout(flex,normal,center);
            margin-bottom: 12px;
            .title {
                font-size: 14px;
                color: #6B6C70;
                font-family: "PingFang SC Medium";
                margin-right: 10px;
                line-height: 20px;
            }
            .name {
                color: #37383A;
                font-size: 14px;
                margin: 0;
            }
            .val {
                color: #37383A;
                font-size: 14px;
                width: 100%;
                max-height: 600px;
                display: flex;
                flex-direction: column;
                align-items: center;
                margin: 0;
                p {
                    word-break: break-all;
                }
            }
        }
    }
}
.department-btn {
    max-width: 200px;
    @include textEllipsis();
}

.wechat-mask {
    ::v-deep {
        .el-dialog {
            width: 400px;
            min-width: unset;
            .el-dialog__header {
                border-bottom: 1px solid #9da1a4;
                padding: 20px 0 4px;
                margin: 0 20px;
            }
            .el-dialog__title {
                font-size: 20px;
                font-family: "PingFangSC";
                font-weight: bold;
                line-height: 28px;
                color: #37383a;
            }
            .el-dialog__body {
                height: 540px;
                overflow: scroll;
            }
            .el-dialog__footer {
                padding: 0;
                .dialog-footer {
                    width: 100%;
                    display: flex;
                    button {
                        width: 100%;
                        border-radius: 0;
                    }
                }
            }
        }
    }
}
</style>
